-module(gtp_bearer_server).
-behaviour(gen_server).
-include("protocol.hrl").
-export([start/0,start_link/0,start_link/1,init/1,handle_call/3,handle_cast/2,handle_info/2,terminate/2,code_change/3]).
-export([handle/2]).
-define(SERVER,?MODULE).
-record(gtp_counter,{
	echo_request = 0,
	echo_response = 0,
	create_session_request = 0,
	create_session_response = 0,
	modify_bearer_req = 0,
	modify_bearer_res = 0,
	unknown = 0
	
	}).

handle(Pid,Request) ->
	gen_server:cast(Pid,Request).
	
start()  ->
	case gen_server:start({local, ?SERVER}, ?MODULE, [], []) of 
	{ok,_} ->
		ok;
	{error,{already_started,Pid}} ->
		ok;
	{error,Reason} ->
		error_logger:info_msg("start ~s service failure with ~p~n",[?SERVER,Reason])
	end.
start_link(IP) ->
	gen_server:start_link(?MODULE, [IP], []).

start_link() ->
	start_link(undefined).
	
init(IP) ->
	error_logger:info_msg("gtp bearer server ~w start...",[IP]),
	process_flag(trap_exit, true),
	{ok,{running,IP,#gtp_counter{}}}.
	
handle_call(_,_,_State) ->
	{reply, {error,"no func define gtp server"}, {}}.
	
handle_cast({packet_comming,P_Tuple},{running,IP,Counter}) ->
	case P_Tuple#packet_tuple.packet of
	<<2:3,0:5,?ECHO_REQUEST,_Other/binary>> ->
		{noreply,{running,IP,Counter#gtp_counter{echo_request = Counter#gtp_counter.echo_request + 1}}};
	<<2:3,0:5,?ECHO_RESPONSE,_Other/binary>> ->
		{noreply,{running,IP,Counter#gtp_counter{echo_response = Counter#gtp_counter.echo_response + 1}}};
	<<2:3,0:1,1:1,0:3, ?CREATE_SESSION_REQUEST,_Length:16,0:32,SeqNo:24,_/binary>> ->
		{ok,Pid} = gtp_session_server:start_link(),
		put({SeqNo,create_session},Pid),
		gtp_session_server:handle(Pid,{packet_comming,P_Tuple}),
		{noreply,{running,IP,Counter#gtp_counter{create_session_request = Counter#gtp_counter.create_session_request + 1}}};
	<<2:3,0:1,1:1,0:3, ?CREATE_SESSION_RESPONSE,_Length:16,0:32,SeqNo:24,_/binary>> ->
		Pid = get({SeqNo,create_session}),
		gtp_session_server:handle(Pid,{packet_comming,P_Tuple}),
		{noreply,{running,IP,Counter#gtp_counter{create_session_response = Counter#gtp_counter.create_session_response + 1}}};
	_ ->
		{noreply,{running,IP,Counter#gtp_counter{unknown = Counter#gtp_counter.unknown + 1}}}
	end;
		
handle_cast(_, State) ->
	{noreply,State}.
handle_info(_, State) ->
	{noreply,State}.
terminate(_, _) ->
	ok.
code_change(_, State, _) ->
	{ok,State}.	
	